package oot.fragment;

import java.util.ArrayList;

import oot.activity.FlashScreenActivity;
import oot.activity.ListFollowersActivity;
import oot.activity.ListFollowingsActivity;
import oot.activity.LoginActivity;
import oot.activity.ProfileActivity;
import oot.activity.ViewTweetFavoriteActivity;
import oot.activity.ViewUserTweetActivity;
import oot.data.Config;
import oot.data.Connection;
import oot.data.JSonPaser;
import oot.data.Tweet;
import oot.data.User;
import oot.tab.activity.R;
import oot.view.HeadTab;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import ott.adapter.FollowerAdapter;
import ott.adapter.TweetAdapter;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

@SuppressLint({ "ParserError", "ParserError", "ParserError" })
public class MeFragment extends Fragment {
	private Button btLogout;
	private Button btViewAllTweet;
	private Button btEditProfile;
	private Button btnFollow;
	private Button btViewTweetFavorite;
	private AQuery aQuery;
	private String response;
	private int followers;
	private int followings;
	private int tweets;
	private User user;
	private JSONObject js;
	private LinearLayout loShowUserTweet;
	private ArrayList<Tweet> result;
	private ArrayList<User> listSuggest;
	private LinearLayout listSuggestView;
	private FollowerAdapter suggestAdapter;
	private boolean followStatus;
	private LinearLayout me_btn_tweet;
	private LinearLayout me_btn_followings;
	private LinearLayout me_btn_followers;

	public User getUser() {
		return user;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		if (getActivity() instanceof ProfileActivity) {
			HeadTab h = new HeadTab(getActivity());
			h.createHeadTabAction("@" + user.getUserName());
		}
	}

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

	}

	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.me_screen_layout, container, false);
		loShowUserTweet = (LinearLayout) v
				.findViewById(R.id.lo_me_screen_tweet_area);
		aQuery = new AQuery(v);
		btViewAllTweet = (Button) v
				.findViewById(R.id.bt_me_screen_view_all_tweet);
		btViewTweetFavorite = (Button) v.findViewById(R.id.me_btnfavorite);
		btEditProfile = (Button) v.findViewById(R.id.me_btnEditProfile);
		btnFollow = (Button) v.findViewById(R.id.me_btnFollow);
		user = (User) getActivity().getIntent().getSerializableExtra("user");
		listSuggest = new ArrayList<User>();
		listSuggestView = (LinearLayout) v.findViewById(R.id.me_suggest);
		me_btn_tweet = (LinearLayout) v.findViewById(R.id.me_btn_tweet);
		me_btn_followers = (LinearLayout) v.findViewById(R.id.me_btn_followers);
		me_btn_followings = (LinearLayout) v.findViewById(R.id.me_btn_followings);
		
		suggestAdapter = new FollowerAdapter(listSuggest, getActivity()
				.getApplicationContext());
		if (user == null) {
			Uri data = getActivity().getIntent().getData();
			if (data != null) {
				String url = data.toString();
				try {
					JSONObject obj = new JSONObject(url.substring(url
							.indexOf("{")));
					user = JSonPaser.paserUser(obj.getJSONObject("User"));
					// mUser.setUserName(url.substring(url.indexOf("@") + 1));
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		js = new JSONObject();
		doGetUserTweets(user.getUserID(), "-1", "3");
		btViewTweetFavorite.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent i = new Intent(getActivity().getApplicationContext(),
						ViewTweetFavoriteActivity.class);
				i.putExtra(Config.USER, user);
				startActivity(i);
			}
		});
		
		btViewAllTweet.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent i = new Intent(getActivity().getApplicationContext(),
						ViewUserTweetActivity.class);
				i.putExtra(Config.USER, user);
				startActivity(i);
			}
		});
		me_btn_tweet.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent i = new Intent(getActivity().getApplicationContext(),
						ViewUserTweetActivity.class);
				i.putExtra(Config.USER, user);
				startActivity(i);
			}
		});
		
		btLogout = (Button) v.findViewById(R.id.me_logout);
		btLogout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				// Connection.post("/", params, responseHandler)
				SharedPreferences sharedPreferences = getActivity()
						.getSharedPreferences("login", Activity.MODE_PRIVATE);

				SharedPreferences.Editor editor = sharedPreferences.edit();
				editor.putBoolean(Config.LOGEDIN, false);
				editor.commit();
				Intent i = new Intent(getActivity().getApplicationContext(),
						LoginActivity.class);
				i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(i);
			}
		});

		btnFollow.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (user.isFollowStatus()) {
					btnFollow.setBackgroundResource(R.drawable.greenbutton);
					btnFollow.setText("Follow");
					unfollow(user.getUserID());
					user.setFollowStatus(false);
				} else {
					btnFollow.setBackgroundResource(R.drawable.bluebutton);
					btnFollow.setText("Unfollow");
					follow(user.getUserID());
					user.setFollowStatus(true);
				}
			}
		});

		aQuery.id(R.id.me_btnfollower).getButton()
				.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View paramView) {
						// TODO Auto-generated method stub
						Intent i = new Intent(getActivity()
								.getApplicationContext(),
								ListFollowersActivity.class);
						i.putExtra("get_userid", user.getUserID());
						startActivity(i);
					}
				});
		
		
		me_btn_followers.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View paramView) {
				// TODO Auto-generated method stub
				Intent i = new Intent(getActivity()
						.getApplicationContext(),
						ListFollowersActivity.class);
				i.putExtra("get_userid", user.getUserID());
				startActivity(i);
			}
		});

		aQuery.id(R.id.me_btnfollowing).getButton()
				.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View paramView) {
						// TODO Auto-generated method stub
						Intent i = new Intent(getActivity()
								.getApplicationContext(),
								ListFollowingsActivity.class);
						i.putExtra("get_userid", user.getUserID());
						startActivity(i);
					}
				});
		
		
		me_btn_followings.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View paramView) {
				// TODO Auto-generated method stub
				Intent i = new Intent(getActivity()
						.getApplicationContext(),
						ListFollowingsActivity.class);
				i.putExtra("get_userid", user.getUserID());
				startActivity(i);
			}
		});

		aQuery.id(R.id.me_screenname).text(user.getUserScreenName());
		aQuery.id(R.id.me_username).text("@" + user.getUserName());
		aQuery.id(R.id.me_avatar).image(
				Connection.BASE_URL_IMAGE + user.getUserAvatarURL(), true,
				true, 0, R.drawable.m05_item_avar);
		getUserInfo();
		suggestUsers();
		hideSection();
		return v;
	}

	private void suggestUsers() {
		RequestParams requestParams = new RequestParams();
		requestParams.put("user_id", FlashScreenActivity.user.getUserID());
		Connection.post("users/suggest", requestParams,
				new AsyncHttpResponseHandler() {
					@Override
					public void onSuccess(String res) {
						super.onSuccess(res);
						if (res != null) {
							if (listSuggest == null) {
								listSuggest = new ArrayList<User>();
							} else {
								listSuggest.clear();
							}

							listSuggest = JSonPaser.listSuggests(res,
									listSuggest);
							for (int i = 0; i < suggestAdapter.getCount(); i++) {
								listSuggestView.addView(suggestAdapter.getView(
										i, null, null));
							}
						}
					}
				});
	}

	public void hideSection() {
		if (user.getUserID().equals(FlashScreenActivity.user.getUserID())) {
			btLogout.setVisibility(View.VISIBLE);
			btEditProfile.setVisibility(View.VISIBLE);
		} else {
			btnFollow.setVisibility(View.VISIBLE);
			if (followStatus) {
				btnFollow.setBackgroundResource(R.drawable.greenbutton);
				btnFollow.setText("Follow");
			} else {
				btnFollow.setBackgroundResource(R.drawable.bluebutton);
				btnFollow.setText("Unfollow");
			}
		}
	}

	@SuppressWarnings("static-access")
	public void getUserInfo() {

		Connection connection = new Connection();
		RequestParams requestParams = new RequestParams();
		requestParams.put("get_userid", user.getUserID());
		connection.post("users/getusers", requestParams,
				new AsyncHttpResponseHandler() {
					@Override
					public void onSuccess(String res) {
						super.onSuccess(res);
						response = res;
						Log.e("RES",res);
						contentPaser(response);
					}

					@Override
					public void onFailure(Throwable arg0, String res) {
						// TODO Auto-generated method stub
						super.onFailure(arg0, res);
						Toast.makeText(getActivity().getApplicationContext(),
								"Get user infor faile", Toast.LENGTH_LONG)
								.show();
					}
				});

	}

	public void contentPaser(String pString) {
		if (pString == null) {
			Toast.makeText(getActivity().getApplicationContext(),
					"Get user infor faile", Toast.LENGTH_LONG).show();
		} else {
			JSONObject jsonObject;
			try {
				jsonObject = new JSONObject(pString);
				if (jsonObject.getInt("status_code") == 0) {
					JSONObject js = jsonObject.getJSONArray("entity")
							.getJSONObject(0);
					followers = js.getInt("followers");
					followings = js.getInt("followings");
					tweets = js.getInt("tweets");
					followStatus = js.getBoolean("followStatus");
					aQuery.id(R.id.me_follower).text("" + followers);
					aQuery.id(R.id.me_following).text("" + followings);
					aQuery.id(R.id.me_tweet).text("" + tweets);
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}

		}
	}

	public void follow(String userId) {
		RequestParams requestParams = new RequestParams();
		requestParams.put("followedId", "" + userId);
		Log.e("FID", "FID: " + userId);
		Connection.post("follows/follow", requestParams,
				new AsyncHttpResponseHandler() {
					@Override
					public void onSuccess(String res) {
						super.onSuccess(res);
						Log.e("RES", "" + res);
					}

					@Override
					public void onFailure(Throwable arg0, String res) {
						// TODO Auto-generated method stub
						super.onFailure(arg0, res);
						Log.e("RES", "" + res);
					}
				});
	}

	public void unfollow(String userId) {
		RequestParams requestParams = new RequestParams();
		requestParams.put("followedId", "" + userId);
		Log.e("FID", "UFID: " + userId);
		Connection.post("follows/unfollow", requestParams,
				new AsyncHttpResponseHandler() {
					@Override
					public void onSuccess(String res) {
						super.onSuccess(res);
						Log.e("RES", "" + res);
					}

					@Override
					public void onFailure(Throwable arg0, String res) {
						// TODO Auto-generated method stub
						super.onFailure(arg0, res);
						Log.e("RES", "" + res);
					}
				});
	}

	public void doGetUserTweets(String userId, String min, String count) {
		
		String api = "/Timelines/user_timeline";
		RequestParams params = new RequestParams();
		params.put("user_id", userId);
		params.put("max_tweet_id", min);
		params.put("count", count);
		Log.i("test", params.toString());
		// Connection.setBaseURL("http://192.168.1.9");
		Connection.post(api, params, new AsyncHttpResponseHandler() {
			public void onSuccess(String arg0) {
				Log.i("test", "return --------" + arg0);
				super.onSuccess(arg0);
				try {
					js = new JSONObject(arg0);
					if (js.getInt("status_code") != 0) {
						// show error message if error occur
					} else {
						JSONArray jsTweets = (JSONArray) js.get("entity");
						if(result == null){
							result = new ArrayList<Tweet>();
						}else{
							result.clear();
						}
						for (int i = 0; i < jsTweets.length(); i++) {
							// add to list tweet
							result.add(JSonPaser
									.paserTweet((JSONObject) jsTweets.get(i)));
						}
						TweetAdapter tweetAdater = new TweetAdapter(
								getActivity().getApplicationContext(), result);
						for (int i = 0; i < tweetAdater.getCount(); i++) {
							loShowUserTweet.addView(tweetAdater.getView(i,
									null, null));
						}
						// result.add(object)
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
	}
}
